package main

import (
	"fmt"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"
	"qld2devservice/cons"
	"qld2devservice/handler"
	"qld2devservice/models"
	"qld2devservice/proto"
	"qld2devservice/service"
	"qld2devservice/utils"
	"strconv"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"google.golang.org/grpc"
)

func main() {
	var err error

	sqlconn, err := utils.Config.Get("sqlconn")
	if cons.GRPC_TEST_MODE == cons.ENUM_SERVER {
		sqlconn, err = utils.Config.Get("localsqlconn")
	} else if cons.GRPC_TEST_MODE == cons.ENUM_SERVER_TEST {
		sqlconn, err = utils.Config.Get("testsqlconn")
	} else if cons.GRPC_TEST_MODE == cons.ENUM_LOCALHOST {
		sqlconn, err = utils.Config.Get("localtestsqlconn")
	}
	fmt.Println("sqlconn:", sqlconn)
	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, "conf get failed, err:", err.Error())
		os.Exit(1)
	}

	models.DB, err = gorm.Open("mysql", sqlconn)
	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, "mysql open failed, err:", err.Error())
		os.Exit(1)
	} else {
		defer func() {
			err1 := models.DB.Close()
			if err != nil {
				utils.MyPrint(utils.PRINT_ERROR, "mysql close failed, err:", err1)
			}
		}()
		//一个坑，不设置这个参数，gorm会把表名转义后加个s，导致找不到数据库的表1
		models.DB.SingularTable(true)
		// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
		models.DB.DB().SetMaxIdleConns(100)
		// SetMaxOpenConns sets the maximum number of open connections to the database.
		models.DB.DB().SetMaxOpenConns(100)
		// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
		models.DB.DB().SetConnMaxLifetime(time.Hour)
		if utils.MyPrintLogGrade > 0 {
			models.DB.LogMode(true)
		}
	}

	service.MqttInit()
	service.RedisConnect()
	service.ErrorMsgInit()

	//临时——start
	//onlineList, err := service.RedisKeyListNoHeader("online")
	//if err != nil {
	//	utils.MyPrint(utils.PRINT_ERROR, err.Error(), "GetAllDevice:redis获取online列表失败")
	//}
	//fmt.Println("打印长度:", len(onlineList))
	//for i := 0; i < len(onlineList); i++ {
	//	if onlineList[i] == "/qld2devservice/q33012403003285/online" {
	//		fmt.Println("找到了：", onlineList[i])
	//	}
	//
	//}
	//
	//onlineSnNumList := make(map[string]bool)
	//for i := 0; i < len(onlineList); i++ {
	//	result := strings.Split(onlineList[i], "/")
	//	if onlineList[i] == "/qld2devservice/q33012403003285/online" {
	//		fmt.Println("找到了数组下表2：", result[0])
	//		fmt.Println("找到了数组：", result)
	//	}
	//	if len(result) > 2 {1
	//		onlineSnNumList[result[2]] = true
	//	}
	//}
	//
	//devices, err := models.GetAllQldOutletSnNumAndTypeAndStatus()
	//for i := 0; i < len(devices); i++ {
	//	if _, ok := onlineSnNumList[devices[i].SnNum]; !ok {
	//		if devices[i].AreaId == 7293 || devices[i].AreaId == 7292 || devices[i].AreaId == 7282 || devices[i].AreaId == 7281 || devices[i].AreaId == 6915 || devices[i].AreaId == 7251 || devices[i].AreaId == 7253 || devices[i].AreaId == 7254 {
	//			fmt.Println("桩号不存在：", devices[i].SnNum, ":", onlineSnNumList[devices[i].SnNum])
	//		}
	//
	//	}
	//}
	//fmt.Println("打印onlineSnNumList长度：", len(onlineSnNumList), "key:", onlineSnNumList["q33012403003285"])
	//return
	//临时——end

	err = service.GetAllDevice()

	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, "GetAllDevice failed, err:", err.Error())
		os.Exit(1)
	}

	PORT, err := utils.Config.Get("port")
	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, err.Error())
		os.Exit(1)
	}

	utils.MyPrint(utils.PRINT_DEBUG, 6)
	//address, _ := utils.Config.Get("redisAddressTest")
	//fmt.Println("链接的redis地址:", address)
	listener, err := net.Listen("tcp", ":"+PORT)
	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, utils.PRINT_ERROR, "failed to listen1: %v", err.Error())
	}
	utils.MyPrint(utils.PRINT_WARN, utils.PRINT_WARN, "listen on:", PORT)

	//通过http://ip:6060/myPrintLogGrade?value=3 动态设置myPrintLogGrade
	//通过kubectl get pods -n qld2-test -o wide命令可以获得其ip
	http.HandleFunc("/myPrintLogGrade", func(rw http.ResponseWriter, r *http.Request) {
		keys, ok := r.URL.Query()["value"]
		if !ok || len(keys) < 1 {
		} else if myPrintLogGrade, err := strconv.ParseInt(keys[0], 10, 64); err != nil {
			utils.MyPrint(utils.PRINT_ERROR, "myPrintLogGrade set err, ", err.Error())
		} else {
			utils.MyPrintLogGrade = myPrintLogGrade
		}
		response := fmt.Sprintln("myPrintLogGrade = ", utils.MyPrintLogGrade)
		utils.MyPrint(utils.PRINT_ERROR, response)
		rw.Write([]byte(response))
	})
	go http.ListenAndServe("0.0.0.0:6060", nil)
	// 2. 开启 http 服务
	go http.ListenAndServe(":9984", nil)

	server := grpc.NewServer()
	proto.RegisterDevServer(server, handler.NewDevController())
	proto.RegisterDevMqttServer(server, handler.NewDevMqttController())
	proto.RegisterDevOrderServer(server, handler.NewDevOrderController())
	proto.RegisterDevCloseForceServer(server, handler.NewDevCloseForceController())
	proto.RegisterDevCloseForceCardServer(server, handler.NewDevCloseForceCardController())
	if err := server.Serve(listener); err != nil {
		utils.MyPrint(utils.PRINT_ERROR, "failed to serve: %v", err.Error())
	}
}
